<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\service;

use app\index\model\BalanceBill;
use app\index\model\Order;
use app\index\model\UserCash;
use think\Exception;
use think\facade\Db;

class BalanceSerivce
{
    private $money = null;
    private $user_cash;


    public function getMoney() : ?float{
        return $this->money;
    }


    public function setMoney(Order $order) : void{
        $money = $order->money;
        $discount = bcadd($order->discount,$order->discount_amount,2);
        $money = bcsub($money,$discount,2);
        $this->money = $money;
    }


    public function setUserCash(int $user_id) : void{
        $this->user_cash = UserCash::find($user_id);
    }
    public function balanceJudge() : void{
        $balance = $this->user_cash->total;
        if ($this->money > $balance)
            throw new Exception('余额不足',HTTP_INVALID);
    }

    public function balanceGeneralAverage(array $orderCommodity) : void{
        $sql = '';
        foreach ($orderCommodity AS $key => $value){
            $money = bcsub($value['money'] , $value['discount'],2);
            $money = bcsub($money,$value['discount_amount'],2);
            $sql .= "when id = {$value['id']} then {$money}";
        }
        $sql = 'update order_commodity set status = 2,discount_balance = case '.$sql.' else 0 end where order_id = '.$value['order_id'];
        Db::query($sql);
    }


    public function balanceDeduction(int $order_id) : void{
        BalanceBill::create([
            'order_id' => $order_id,
            'user_id' => $this->user_cash->user_id,
            'amount' => $this->money,
            'status' => 1,
            'type' => 1,
            'create_time' => now()
        ]);
        Db::name('user_cash')
            ->where('user_id',$this->user_cash->user_id)
            ->dec('total',$this->money)
            ->update(['update_time' => now()]);
    }
}